package com.lhsy.djcloud.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.common.SecurityConstant;
import com.lhsy.djcloud.controller.vo.LoginUserVo;
import com.lhsy.djcloud.entity.Department;
import com.lhsy.djcloud.entity.Employee;
import com.lhsy.djcloud.entity.User;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.DepartmentService;
import com.lhsy.djcloud.service.EmployeeService;
import com.lhsy.djcloud.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 *
 * @author kate
 */
@RestController
@Api(value = "Server-API",tags = "用户登录相关接口")
@Slf4j
public class LoginController extends BaseController{
    @Autowired private RedisTemplate<String,String> redisTemplate;
    @Autowired private UserService userService;
    @Autowired private DepartmentService departmentService;
    @Autowired private EmployeeService employeeService;

    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ReturnT login(@RequestBody LoginUserVo loginUserVo,HttpServletRequest request){
        if (Objects.isNull(loginUserVo)){
            return ReturnT.FAIL;
        }
        if (StrUtil.isEmpty(loginUserVo.getLoginName())){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"请输入用户名");
        }
        if (StrUtil.isEmpty(loginUserVo.getPassword())){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"请输入密码");
        }
        if (StrUtil.isEmpty(loginUserVo.getVerCode())){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"请输入验证码");
        }
        log.info("登录验证码:{},random:{},cap:{}",loginUserVo.getVerCode(),loginUserVo.getRandomStr(),redisTemplate.opsForValue().get(loginUserVo.getRandomStr()));
        String loginCaptcha = redisTemplate.opsForValue().get(loginUserVo.getRandomStr());
        if (!loginUserVo.getVerCode().equals(loginCaptcha)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"验证码不正确");
        }

        User user = userService.selectByUserName(loginUserVo.getLoginName());
        if (Objects.isNull(user)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"用户名密码不正确");
        }
        //校验密码
        if (!user.getPassword().equals(SecureUtil.md5(loginUserVo.getPassword()))){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"用户名密码不正确");
        }
        Department department = departmentService.getById(user.getDeptId());
        UserDto userDto = new UserDto();
        userDto.setUserId(user.getId());
        userDto.setTenantId(user.getTenantId());
        userDto.setUserName(user.getUsername());
        userDto.setDepartment(department);
        userDto.setRoleName(user.getRoleName());
        userDto.setUserface(user.getUserface());
        //设置党员信息
        if (Objects.nonNull(department.getEmployeeId())){
            Employee employee = employeeService.getById(department.getEmployeeId());
            userDto.setEmployee(employee);
        }
        String oldToken = redisTemplate.opsForValue().get(SecurityConstant.USER_TOKEN_PRE + loginUserVo.getLoginName());
        //失效之前的token
        if(StrUtil.isNotBlank(oldToken)){
            redisTemplate.delete(SecurityConstant.TOKEN__USER_PRE + oldToken);
            redisTemplate.delete(SecurityConstant.USER_TOKEN_PRE + loginUserVo.getLoginName());
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        // 将信息登陆信息存储到redis
        redisTemplate.opsForValue().set(SecurityConstant.USER_TOKEN_PRE + loginUserVo.getLoginName(), token);
        redisTemplate.opsForValue().set(SecurityConstant.TOKEN__USER_PRE + token, JSONUtil.toJsonStr(userDto));
        Map params = Maps.newHashMap();
        params.put("accessToken",token);
        params.put("time", System.currentTimeMillis());
        params.put("user", userDto);
        return ReturnT.SUCCESS(params);

    }

    @ApiOperation(value = "用户登出")
    @RequestMapping(value = "/loginout",method = RequestMethod.GET)
    public ReturnT loginOut(HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        String oldToken = redisTemplate.opsForValue().get(SecurityConstant.USER_TOKEN_PRE + currUser.getUserName());
        //失效之前的token
        if(StrUtil.isNotBlank(oldToken)){
            redisTemplate.delete(SecurityConstant.TOKEN__USER_PRE + oldToken);
            redisTemplate.delete(SecurityConstant.USER_TOKEN_PRE + currUser.getUserName());
        }
        return ReturnT.SUCCESS;
    }
}
